public class CountAndSay {

    public String countAndSay(int n) {
        if (n == 1) return "1";

        String last = countAndSay(n - 1);
        char[] chars = last.toCharArray();
        int length = chars.length;
        StringBuffer stringBuffer = new StringBuffer();
        if (length == 1) {
            stringBuffer.append(1);
            stringBuffer.append(chars[0]);
            return stringBuffer.toString();
        }
        int sum = 1;
        for (int i = 0; i < length - 1; i++) {
            if (chars[i] == chars[i + 1]) {
                sum++;
            } else {
                stringBuffer.append(sum);
                stringBuffer.append(chars[i]);
                sum = 1;
            }
        }
        stringBuffer.append(sum);
        stringBuffer.append(chars[length - 1]);
        return stringBuffer.toString();
    }
}
